package com.mywebbox.mycraftplugin;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MyCraftPlugin extends JavaPlugin {
//essai
	static final Logger log = Logger.getLogger("Minecraft");

	@Override
	public void onEnable() {
		PluginManager pm = getServer().getPluginManager();
		pm.registerEvents(new MyCraftPluginEvents(this), this);
		log.info(I18n._("onEnablePlugin"));
	}

	@Override
	public void onDisable() {
		log.info(I18n._("onDisablePlugin"));
	}

	@Override
	public boolean onCommand(CommandSender sender, Command cmd,
			String commandLabel, String[] args) {
		boolean myOnCommand = myOnCommand(sender, cmd, commandLabel, args);

		if (!myOnCommand) {
			String[] params = { cmd.getName() };
			sender.sendMessage(I18n._("canNotRunCommand", params));
		}

		return myOnCommand;
	}

	public boolean myOnCommand(CommandSender sender, Command cmd,
			String commandLabel, String[] args) {
		String commandClass = commandLabel.substring(0, 1).toUpperCase()
				+ commandLabel.substring(1).toLowerCase() + "Command";
		String commandPackage = this.getClass().getPackage().getName()
				+ ".commands";

		try {
			Class<?> classCommand = Class.forName(commandPackage + "."
					+ commandClass);
			Constructor<?> constructorCommand = classCommand.getConstructor(
					CommandSender.class, Command.class, String.class,
					String[].class, MyCraftPlugin.class);
			Object objectCommand = constructorCommand.newInstance(sender, cmd,
					commandLabel, args, this);
			Method method = classCommand.getMethod("runCommand");
			return method.invoke(objectCommand).equals(true);
		} catch (ClassNotFoundException ex) {
			log.log(Level.WARNING,
					I18n._("canNotRunCommand.ClassNotFoundException"));
		} catch (NoSuchMethodException ex) {
			log.log(Level.WARNING,
					I18n._("canNotRunCommand.NoSuchMethodException"));
		} catch (SecurityException ex) {
			log.log(Level.WARNING, I18n._("canNotRunCommand.SecurityException"));
		} catch (InstantiationException ex) {
			log.log(Level.WARNING,
					I18n._("canNotRunCommand.InstantiationException"));
		} catch (IllegalAccessException ex) {
			log.log(Level.WARNING,
					I18n._("canNotRunCommand.IllegalAccessException"));
		} catch (IllegalArgumentException ex) {
			log.log(Level.WARNING,
					I18n._("canNotRunCommand.IllegalArgumentException"));
		} catch (InvocationTargetException ex) {
			log.log(Level.WARNING,
					I18n._("canNotRunCommand.InvocationTargetException"));
		}

		return false;
	}

}
